/**
 * Created with IntelliJ IDEA.
 * User: ajhin
 * Date: 7/15/12
 * Time: 8:05 PM
 * To change this template use File | Settings | File Templates.
 */
package com.societyGames.utility
{
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.xml.XMLDocument;

public class XMLUtility
{
    public static function loadXMLFromClass(xmlClass:Class):XML
    {
        var byteArray:ByteArray = ByteArray(new xmlClass());
        return new XML(byteArray.readUTFBytes(byteArray.length));
    }

    private static var callbackURLLoaders:Dictionary = new Dictionary(); /*CallbackURLLoader -> boolean*/

    public static function loadXMLFromURL(url:String, callback:Function /*function(xml:XML):void*/):void
    {
        var urlLoader:CallbackURLLoader = new CallbackURLLoader();
        urlLoader.callback = callback;
        //set the loaders listener function that gets the event when the xml is loaded
        urlLoader.addEventListener(Event.COMPLETE, onXMLLoaded);
        //Store it so it's not gc'd.
        callbackURLLoaders[urlLoader] = true;
        //load the xml file from it's location
        urlLoader.load(new URLRequest(url));
    }

    private static function onXMLLoaded(event:Event):void
    {
        var urlLoader:CallbackURLLoader = CallbackURLLoader(event.target);
        urlLoader.removeEventListener(Event.COMPLETE, onXMLLoaded);
        //remove from non-gc list
        delete callbackURLLoaders[urlLoader];
        //parse the content and create a xml structure in the XMLDocument
        urlLoader.callback(XML(urlLoader.data));
    }
}
}

import flash.net.URLLoader;
class CallbackURLLoader extends URLLoader
{
    public var callback:Function; /*function(xml:XML):void*/
}
